package ar.com.globallogic.promomr.services;

import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.security.authentication.encoding.Md5PasswordEncoder;
import org.springframework.stereotype.Service;

import ar.com.globallogic.promomr.domain.Folder;
import ar.com.globallogic.promomr.domain.User;
import ar.com.globallogic.promomr.exceptions.UserNameAlreadyExistsException;
import ar.com.globallogic.promomr.exceptions.UserNotFoundException;
import ar.com.globallogic.promomr.persistance.FolderRepository;
import ar.com.globallogic.promomr.persistance.UserRepository;

@Service
public class UserServiceImpl implements UserService {

	private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
	
	private UserRepository userRepository;
	private FolderRepository folderRepository;
	private Md5PasswordEncoder passwordEncoder;
	
	@Autowired
	public UserServiceImpl(UserRepository userRepository, FolderRepository folderRepository, Md5PasswordEncoder passwordEncoder){
		this.userRepository = userRepository;
		this.folderRepository = folderRepository;
		this.passwordEncoder = passwordEncoder;
	}

	public User findOne(String id) {
		logger.info(String.format("Finding user with id %s.", id));
		User user = userRepository.findOne(id);
		if(user == null){
			logger.error(String.format("User with id %s was not found.", id));
			throw new UserNotFoundException(id);
		}
		logger.info(String.format("User with id %s was found.", id));
		return user;
	}

	public User findByUserName(String userName) {
		logger.info(String.format("Finding user with userName %s.", userName));
		List<User> users = userRepository.findByUserName(userName);
		if(users.isEmpty()){
			logger.error(String.format("User with userName %s was not found.", userName));
			throw new UserNotFoundException(userName);
		}
		logger.info(String.format("User with userName %s was found.", userName));
		return users.get(0);
	}

	public User save(User user) {
		try {
			String encodedPassword = passwordEncoder.encodePassword(user.getPassword(), null);
			user.setPassword(encodedPassword);
			Folder userHomeFolder = new Folder(user.getUserName());
			folderRepository.save(userHomeFolder);
			user.setHomeFolder(userHomeFolder);
			userRepository.save(user);
			logger.info(String.format("User with userName %s was saved.", user.getUserName()));
			return user;
		}catch(DuplicateKeyException e){
			logger.error(String.format("User with userName %s already exists.", user.getUserName()));
			throw new UserNameAlreadyExistsException(user.getUserName());
		}
	}
}
